<template>
  <div class="app-container">
    <el-card>
      <!-- 水厂选择区域 -->
      <div class="header">
        <el-select v-model="currentWaterPlantId" placeholder="请选择水厂" style="width: 300px"
          @change="handleWaterPlantChange">
          <el-option v-for="item in factoryOptions" :key="item.dictValue" :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
      </div>

      <!-- 基本信息配置表单 -->
      <el-form :model="basicInfoForm" label-width="120px" class="mt-3" :rules="rules" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="水厂名称" prop="waterPlantName">
              <el-input v-model="basicInfoForm.waterPlantName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建成日期" prop="completionDate">
              <el-date-picker v-model="basicInfoForm.completionDate" type="date" placeholder="选择日期" style="width: 100%"
                value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="日供水量(m³)" prop="dailyWaterSupply">
              <el-input-number v-model="basicInfoForm.dailyWaterSupply" :min="0" :step="1000" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="月供水量(m³)" prop="monthlyWaterSupply">
              <el-input-number v-model="basicInfoForm.monthlyWaterSupply" :min="0" :step="10000" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年供水量(m³)" prop="annualWaterSupply">
              <el-input-number v-model="basicInfoForm.annualWaterSupply" :min="0" :step="100000" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务人口" prop="servedPopulation">
              <el-input-number v-model="basicInfoForm.servedPopulation" :min="0" :step="1000" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="水厂描述" prop="remark">
          <el-input v-model="basicInfoForm.remark" type="textarea" :rows="3" placeholder="请输入水厂描述信息" />
        </el-form-item>

        <!-- 视频配置区域 -->
        <el-divider content-position="left">视频监控配置</el-divider>
        <div v-for="(video, index) in basicInfoForm.videoConfigList" :key="index" class="video-item">
          <el-row :gutter="20" >
            <el-col :span="8">
              <el-form-item :label="`视频${index + 1}名称`" :prop="`videoConfigList.${index}.videoName`"
                :rules="{ required: true, message: '请输入视频名称', trigger: 'blur' }">
                <el-input v-model="video.videoName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="`视频${index + 1}地址`" :prop="`videoConfigList.${index}.videoUrl`"
                :rules="{ required: true, message: '请输入视频地址', trigger: 'blur' }">
                <el-input v-model="video.videoUrl" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="danger" icon="Delete" circle @click="removeVideo(index)" />
            </el-col>
          </el-row>
          <el-form-item :label="`视频${index + 1}描述`" :prop="`videoConfigList.${index}.videoDesc`">
            <el-input v-model="video.videoDesc" type="textarea" :rows="2" />
          </el-form-item>
        </div>

        <el-form-item>
          <el-button type="primary" @click="addVideo">添加视频</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存配置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getFactoryList,
  getWaterPlantBasicInfo,
  saveWaterPlantBasicInfo
} from '@/api/prod_operate/sys_setting/cockpit/info_settings'

// 水厂下拉选项
const factoryOptions = ref([])

// 当前选中的水厂ID
const currentWaterPlantId = ref('')

// 表单引用
const formRef = ref(null)

// 基本信息表单
const basicInfoForm = reactive({
  basicInfoId: '',
  waterPlantId: '',
  waterPlantName: '',
  dailyWaterSupply: 0,
  monthlyWaterSupply: 0,
  annualWaterSupply: 0,
  servedPopulation: 0,
  completionDate: '',
  remark: '',
  videoConfigList: [
    {
      videoId: '',
      videoName: '',
      videoUrl: '',
      videoDesc: ''
    }
  ]
})

// 表单验证规则
const rules = reactive({
  waterPlantName: [
    { required: true, message: '请输入水厂名称', trigger: 'blur' }
  ],
  dailyWaterSupply: [
    { required: true, message: '请输入日供水量', trigger: 'blur' }
  ],
  monthlyWaterSupply: [
    { required: true, message: '请输入月供水量', trigger: 'blur' }
  ],
  annualWaterSupply: [
    { required: true, message: '请输入年供水量', trigger: 'blur' }
  ],
  servedPopulation: [
    { required: true, message: '请输入服务人口', trigger: 'blur' }
  ]
})

// 初始化数据
const initData = async () => {
  try {
    // 获取水厂列表
    const res = await getFactoryList()
    factoryOptions.value = res.data

    // 默认选中第一个水厂
    if (factoryOptions.value.length > 0) {
      currentWaterPlantId.value = factoryOptions.value[0].dictValue
      await loadBasicInfo(currentWaterPlantId.value)
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 加载水厂基本信息
const loadBasicInfo = async (waterPlantId) => {
  try {
    const res = await getWaterPlantBasicInfo(waterPlantId)
    Object.assign(basicInfoForm, res.data)

    // 如果没有视频配置，添加一个默认项
    if (!basicInfoForm.videoConfigList || basicInfoForm.videoConfigList.length === 0) {
      basicInfoForm.videoConfigList = [
        {
          videoId: '',
          videoName: '',
          videoUrl: '',
          videoDesc: ''
        }
      ]
    }
  } catch (error) {
    console.error('获取水厂基本信息失败:', error)
    ElMessage.error('获取水厂基本信息失败')
  }
}

// 处理水厂切换
const handleWaterPlantChange = (waterPlantId) => {
  loadBasicInfo(waterPlantId)
}

// 添加视频配置
const addVideo = () => {
  basicInfoForm.videoConfigList.push({
    videoId: '',
    videoName: '',
    videoUrl: '',
    videoDesc: ''
  })
}

// 移除视频配置
const removeVideo = (index) => {
  if (basicInfoForm.videoConfigList.length > 1) {
    basicInfoForm.videoConfigList.splice(index, 1)
  } else {
    ElMessage.warning('至少需要保留一个视频配置')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 确保waterPlantId正确
    basicInfoForm.waterPlantId = currentWaterPlantId.value

    await saveWaterPlantBasicInfo(basicInfoForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.video-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.mt-2 {
  margin-top: 8px;
}

.mt-3 {
  margin-top: 16px;
}

.el-divider {
  margin: 20px 0;
}
</style>